import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage, ElLoading } from 'element-plus'


// 错误处理
function showMessage(errMsg: string = '网络好像有点问题') {
    ElMessage.error(errMsg)
}

// loading 加载。。。
let loading: any;
// 开始loading
function startLoading() {
    interface Options {
        lock: boolean;
        text: string;
        background: string;
    };

    const options: Options = {
        lock: true,
        text: "加载中...",
        background: 'rgba(0,0,0,0.7)'
    }
    loading = ElLoading.service(options);

}


// 结束loading
function endLoading() {
    loading.close();
}

axios.interceptors.request.use((config: AxiosRequestConfig) => {
    // 加载
    startLoading();
    if (config.method == 'get') {
        config.headers.post['Content-Type'] = 'multipart/form-data;charset=UTF-8'
    } else {
        config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    }


    // 请求拦截
    console.log('请求拦截', config)
    return config
}, (err: Error) => {
    return err
})



axios.interceptors.response.use((response: AxiosResponse) => {
    // 结束loading
    endLoading();
    // 响应拦截器 将数据解构一层
    const { data } = response
    console.log('响应拦截', data)
    return data
}, (err: Error) => {
    console.log('响应拦截 错误', err)
    showMessage(err.message)
    return err
})




export default axios